package com.jspgou.cms.action.admin.main;

import static com.jspgou.common.page.SimplePage.cpn;
import static com.jspgou.common.web.Constants.LIST_SPLIT;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.SimpleFSDirectory;
import org.hibernate.ObjectNotFoundException;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;

import com.jspgou.cms.Constants;
import com.jspgou.cms.entity.Brand;
import com.jspgou.cms.entity.Category;
import com.jspgou.cms.entity.Exended;
import com.jspgou.cms.entity.ShopTuijian;
import com.jspgou.cms.entity.Product;
import com.jspgou.cms.entity.ProductExended;
import com.jspgou.cms.entity.ProductExt;
import com.jspgou.cms.entity.ProductFashion;
import com.jspgou.cms.entity.ProductStandard;
import com.jspgou.cms.entity.ProductType;
import com.jspgou.cms.entity.ProductTypeProperty;
import com.jspgou.cms.entity.StandardType;
import com.jspgou.cms.lucene.LuceneProductSvc;
import com.jspgou.cms.manager.BrandMng;
import com.jspgou.cms.manager.CategoryMng;
import com.jspgou.cms.manager.ExendedMng;
import com.jspgou.cms.manager.ShopTuijianMng;
import com.jspgou.cms.manager.ProductExtMng;
import com.jspgou.cms.manager.ProductFashionMng;
import com.jspgou.cms.manager.ProductMng;
import com.jspgou.cms.manager.ProductStandardMng;
import com.jspgou.cms.manager.ProductTagMng;
import com.jspgou.cms.manager.ProductTypeMng;
import com.jspgou.cms.manager.ProductTypePropertyMng;
import com.jspgou.cms.manager.StandardMng;
import com.jspgou.cms.manager.StandardTypeMng;
import com.jspgou.cms.web.SiteUtils;
import com.jspgou.common.image.ImageUtils;
import com.jspgou.common.page.Pagination;
import com.jspgou.common.web.CookieUtils;
import com.jspgou.common.web.RequestUtils;
import com.jspgou.common.web.ResponseUtils;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.Website;
import com.jspgou.core.manager.LogMng;
import com.jspgou.core.web.WebErrors;

@Controller
public class ProductAct implements ServletContextAware {
	private static final Logger log = LoggerFactory.getLogger(ProductAct.class);
	
	/**
	 * 
	 * @param ctgId
	 * @param source 商品来源
	 * @param Ontheshelf 是否上架
	 * @param Whetherban 是否禁售
	 * @param Whetherpresale 是否预售
	 * @param typeId
	 * @param startSalePrice
	 * @param endSalePrice
	 * @param startStock
	 * @param endStock
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/product/v_list.do")
	public String list(Long ctgId,Long source,Boolean Ontheshelf,Boolean Whetherban,
			Boolean Whetherpresale,Long typeId,Double startSalePrice,Double endSalePrice,
			Integer startStock,Integer endStock,Integer pageNo, 
			HttpServletRequest request, ModelMap model) {
		String productName = RequestUtils.getQueryParam(request, "productName");
		productName = StringUtils.trim(productName);
		String brandName = RequestUtils.getQueryParam(request, "brandName");
		brandName = StringUtils.trim(brandName);
		Website web = SiteUtils.getWeb(request);
		if (ctgId != null) {
			model.addAttribute("category", categoryMng.findById(ctgId));
		}
		Pagination pagination = manager.getPage(SiteUtils.getWebId(request),
				ctgId,null, productName,brandName,source,Ontheshelf,Whetherban,
				Whetherpresale, typeId,
				startSalePrice,endSalePrice,startStock,endStock,
				cpn(pageNo), CookieUtils.getPageSize(request));
		List<ProductType> typeList = productTypeMng.getList(web.getId());
		model.addAttribute("typeList",typeList);
		model.addAttribute("productName",productName);
		model.addAttribute("brandName",brandName);
		model.addAttribute("source",source);
		model.addAttribute("Ontheshelf",Ontheshelf);
		model.addAttribute("Whetherban",Whetherban);
		model.addAttribute("Whetherpresale",Whetherpresale);
		model.addAttribute("typeId",typeId);
		model.addAttribute("startSalePrice",startSalePrice);
		model.addAttribute("endSalePrice",endSalePrice);
		model.addAttribute("startStock",startStock);
		model.addAttribute("endStock",endStock);
		model.addAttribute("pagination",pagination);
		model.addAttribute("ctgId",ctgId);
		return "product/list";
	}

	@RequestMapping("/product/v_left.do")
	public String left(HttpServletRequest request, ModelMap model) {
		List<Category> list = categoryMng.getTopList(SiteUtils.getWebId(request));
		// 如果没有商品类别，则不传递数据到视图层，由视图层给出相应提示。
		if (list.size() > 0) {
			Category treeRoot = new Category();
			treeRoot.setName(MessageResolver.getMessage(request,
					"product.allCategory"));
			treeRoot.setChild(new LinkedHashSet<Category>(list));
			model.addAttribute("treeRoot", treeRoot);
		}
		return "product/left";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/product/v_add.do")
	public String add(Long ctgId, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateAdd(ctgId, request);
		Website site=SiteUtils.getWeb(request);
		String uploadRoot=site.getUploadUrl();
		model.addAttribute("uploadRoot", uploadRoot);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Category category= categoryMng.findById(ctgId);
		// 模型项列表
		List<ProductTypeProperty> itemList = productTypePropertyMng.getList(category.getType().getId(), false);
		List<StandardType> standardTypeList =standardTypeMng.getList(category.getId());
		List<ProductType> typeList = productTypeMng.getList(1L);
		List<Brand> brandList = brandMng.getAllList();
		model.addAttribute("brandList", brandList);
		model.addAttribute("typeList", typeList);
		model.addAttribute("ctgId", ctgId);
		model.addAttribute("category", category);
		model.addAttribute("categoryList", categoryMng.getListForProduct(SiteUtils.getWebId(request), ctgId));
		model.addAttribute("tagList", productTagMng.getList(SiteUtils.getWebId(request)));
		model.addAttribute("standardTypeList", standardTypeList);
		model.addAttribute("itemList", itemList);
		List<Exended> exendeds = exendedMng.getList(category.getType().getId());
		Map map= new HashMap(); 
		Map map1= new HashMap(); 
		int num = exendeds.size();
	    for(int i=0;i<num;i++){
			map.put(exendeds.get(i).getId().toString(), exendeds.get(i).getItems());
			map1.put(exendeds.get(i).getId().toString(), exendeds.get(i));
		}
		model.addAttribute("map", map);
		model.addAttribute("map1", map1);
		return "product/add";
	}
	
	// AJAX请求，不返回页面
		@RequestMapping("/product/v_search.do")
		public void search(Long storeId,Long correlationtypeId,Long correlationbrandId,String correlationproductName,
				HttpServletRequest request, HttpServletResponse response,
				ModelMap model) {
			List<Product> list = productMng.getList(storeId,correlationtypeId, correlationbrandId, correlationproductName);
			JSONObject json=new JSONObject();
			try {
				for (int i=0 ,j=list.size(); i < j; i++) {
						json.append(list.get(i).getId() + "", list.get(i).getName());
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			ResponseUtils.renderJson(response, json.toString());
		}
		
		@RequestMapping("/product/v_combinationsearch.do")
		public void combinationsearch(Long storeId,Long combinationtypeId,Long combinationbrandId,String combinationproductName,
				HttpServletRequest request, HttpServletResponse response,
				ModelMap model) {
			List<Product> list = productMng.getList(storeId,combinationtypeId, combinationbrandId, combinationproductName);
			JSONObject json=new JSONObject();
			try {
				for (int i=0 ,j=list.size(); i < j; i++) {
						json.append(list.get(i).getId() + "", list.get(i).getName());
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			ResponseUtils.renderJson(response, json.toString());
		}
		
		
	
	
	
	@RequestMapping("/product/v_error.do")
	public String error(HttpServletRequest request, ModelMap model) {
		return "product/error";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/product/v_edit.do")
	public String edit(Long id, Long ctgId, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		Website site=SiteUtils.getWeb(request);
		String uploadRoot=site.getUploadUrl();
		model.addAttribute("uploadRoot", uploadRoot);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Product product = manager.findById(id);
		List<ProductStandard> psList = productStandardMng.findByProductId(id);
		String productKeywords = StringUtils.join(product.getKeywords(),LIST_SPLIT);// 模型项列表
		Category category= product.getCategory(); 	
		List<StandardType> standardTypeList = standardTypeMng.getList(category.getId());
		List<ProductTypeProperty> itemList = productTypePropertyMng.getList(category.getType().getId(), false);
		List<ProductExended> pelist=product.getExendeds();
		List<Exended> exendeds = exendedMng.getList(category.getType().getId());
		Map map= new HashMap(); 
		Map map1= new HashMap(); 
		int num = exendeds.size();
	    for(int i=0;i<num;i++){
			map.put(exendeds.get(i).getId().toString(), exendeds.get(i).getItems());
			map1.put(exendeds.get(i).getId().toString(), exendeds.get(i));
		}
	    Map map2=new HashMap();
      	for(int i=0;i<pelist.size();i++){
		   map2.put(pelist.get(i).getName(), pelist.get(i).getValue());
	    }
    	model.addAttribute("map", map);
		model.addAttribute("map1", map1);
    	List<ProductType> typeList = productTypeMng.getList(1L);
		List<Brand> brandList = brandMng.getAllList();
		model.addAttribute("brandList", brandList);
		model.addAttribute("typeList", typeList);
	    model.addAttribute("map2", map2);
	
		model.addAttribute("productKeywords", productKeywords);
		model.addAttribute("tagList", productTagMng.getList(SiteUtils.getWebId(request)));
		model.addAttribute("categoryList", categoryMng.getList(SiteUtils.getWebId(request)));
		model.addAttribute("standardTypeList",standardTypeList);
		model.addAttribute("category", category);
		model.addAttribute("product", product);
		model.addAttribute("ctgId", ctgId);
		model.addAttribute("itemList", itemList);
		model.addAttribute("psList",psList);
		return "product/edit";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/product/o_save.do")
	public String save(Product bean, ProductExt ext, Long ctgId, Long brandId,Long[] storeCategoryIds,
			Long[] tagIds,Long promoteId, String productKeywords,String[] nature,Long[] picture,String[] colorImg,Long[] character,String rightlist,String combinationrightlist, 
			@RequestParam(value = "file", required = false) MultipartFile file,
			String fashionSwitchPic[],Boolean[] isDefaults,Long[] colors,
			Long[] measures,Integer stockCounts[],Integer[] saleCounts,
			Double[] salePrices,Double[] marketPrices,Double[] costPrices,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(bean, file, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		productKeywords = StringUtils.replace(productKeywords, MessageResolver
				.getMessage(request, "product.keywords.split"), LIST_SPLIT);
		String[] keywords = StringUtils.split(productKeywords, LIST_SPLIT);
		Website web = SiteUtils.getWeb(request);
		Map<String, String> exended = RequestUtils.getRequestMap(request, "exended_");
	    List li=new ArrayList(exended.keySet());
	    String[] names = new String[li.size()];
	    String[] values =  new String[li.size()];
	    for(int i=0;i<li.size();i++){
	    	names[i]=(String) li.get(i);
	    	values[i]=exended.get(li.get(i));
	    }
	    if(stockCounts!=null){
	    	bean.setStockCount(getstockCounts(stockCounts));
	    }
	    bean.setAttr( RequestUtils.getRequestMap(request, "attr_"));
		bean = manager.save(bean, ext, web.getId(), ctgId, brandId, storeCategoryIds,tagIds,promoteId,
				keywords,names,values,fashionSwitchPic, file);
		manager.addCorrelation(bean,getProductIds(rightlist));
		manager.addCombination(bean, getProductIds(combinationrightlist));
		 if(picture!=null){
				for(int i =0;i<picture.length;i++){
					ProductStandard ps=new ProductStandard();
					ps.setImgPath(colorImg[i]);
					ps.setType(standardMng.findById(picture[i]).getType());
					ps.setProduct(bean);
					ps.setStandard(standardMng.findById(picture[i]));
					ps.setDataType(true);
					productStandardMng.save(ps);
				}
			}
		   if(character!=null){
			   for(int i =0;i<character.length;i++){
					ProductStandard ps=new ProductStandard();
					ps.setType(standardMng.findById(character[i]).getType());
					ps.setProduct(bean);
					ps.setStandard(standardMng.findById(character[i]));
					ps.setDataType(false);
					productStandardMng.save(ps);
				}
		    }
		saveProductFash(bean,nature,isDefaults,stockCounts,salePrices,marketPrices,costPrices);
		log.info("save Product. id={}", bean.getId());
		logMng.operating(request, "添加商品", "id="+bean.getId()+" ;name="+bean.getName());
		model.addAttribute("message", "global.success");
		model.addAttribute("brandId", brandId);
		return add(ctgId, request, model);
	}
	
	private Integer getstockCounts(Integer stockCounts[]){
		Integer stockCount =0;
		if(stockCounts!=null){
			for(Integer s:stockCounts){
				stockCount  = stockCount + s;
			}
		}
		return stockCount;
	}
	
	

	private void saveProductFash(Product bean,String[] nature,Boolean[] isDefaults,Integer[] stockCounts,
			Double[] salePrices,Double[] marketPrices,Double[] costPrices ){
		if(nature!=null){
			for(int i =0;i<nature.length;i++){
				String[] arr;
				ProductFashion pfash=new ProductFashion();
				pfash.setCreateTime(new Date());
				pfash.setIsDefault(isDefaults[i]);
				pfash.setStockCount(stockCounts[i]);
				pfash.setMarketPrice(marketPrices[i]);
				pfash.setSalePrice(salePrices[i]);
				pfash.setCostPrice(costPrices[i]);
				pfash.setProductId(bean);
				pfash.setNature(nature[i]);
				arr=nature[i].split("_");
				ProductFashion fashion = productFashionMng.save(pfash,arr);
				productFashionMng.addStandard(fashion,arr);
				if(isDefaults[i]){
					bean.setCostPrice(costPrices[i]);
					bean.setMarketPrice(marketPrices[i]);
					bean.setSalePrice(salePrices[i]);
				    manager.update(bean);
				}
			}
		}
	}
	
	
	/*
	 * 更改单个商品禁售状态方法
	 */
	@RequestMapping("/product/o_prohibit.do")
	public String update(Long id,Long ctgId,Integer pageNo, @RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, ModelMap model) {
		Product bean=manager.findById(id);
		WebErrors errors = validateUpdate(bean.getId() ,file,request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		if(bean.getProhibit()!=null&&!bean.getProhibit()){
			bean.setProhibit(true);
		}else{
			bean.setProhibit(false);
		}
		bean = manager.update(bean);
		log.info("update Product. id={}.", bean.getId());
		logMng.operating(request, "修改商品禁售状态", "id="+bean.getId()+" ;name="+bean.getName());
		return "redirect:v_list.do";
	}

	/*
	 * 批量禁售商品
	 */
	@RequestMapping("/product/v_pacthProhibit.do")
	public String pacthProhibit(Long[] ids, Long ctgId,Integer pageNo, HttpServletRequest request,
			ModelMap model){
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		for(Long id:ids){
			Product bean=manager.findById(id);
			bean.setProhibit(false);
			manager.update(bean);
			logMng.operating(request, "修改商品禁售妆太浓", "id="+bean.getId()+" ;name="+bean.getName());
		}
		return "redirect:v_list.do";
	}
	
	/*
	 * 批量取消禁售商品
	 */
	@RequestMapping("/product/v_pacthNotProhibit.do")
	public String pacthNotProhibit(Long[] ids,Integer pageNo, HttpServletRequest request,
			ModelMap model){
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		for(Long id:ids){
			Product bean=manager.findById(id);
			bean.setProhibit(true);
			manager.update(bean);
			logMng.operating(request, "修改商品禁售状态", "id="+bean.getId()+" ;name="+bean.getName());
		}
		return "redirect:v_list.do";
	}
	
	/*
	 * 批量修改售价
	 */
	@RequestMapping("/product/o_salePrice.do")
	public String salePrice(Long[] spwids,Integer pageNo, HttpServletRequest request,
			ModelMap model){
		WebErrors errors = validateDelete(spwids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		for (Long id:spwids) {
			Double price = Double.parseDouble(request.getParameter("salePrice_"+id).trim());
			Product product = manager.findById(id);
			if(product.getProductFashion()!=null){
				ProductFashion pf = product.getProductFashion();
				pf.setSalePrice((double)price);
				productFashionMng.update(pf);
			}else{
				product.setSalePrice((double)price);
				manager.update(product);
			}
			
		}
		return "redirect:v_list.do";
	}
	
	/*
	 * 批量修改库存
	 */
	@RequestMapping("/product/o_stockCount.do")
	public String stockCount(Long[] scwids, Long ctgId,Integer pageNo, HttpServletRequest request,
			ModelMap model){
		WebErrors errors = validateDelete(scwids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		for (Long id:scwids) {
			Integer stockCount = Integer.parseInt(request.getParameter("stockCount_"+id).trim());
			Product product = manager.findById(id);
			product.setStockCount(stockCount);
			manager.update(product);
		}
		return "redirect:v_list.do";
	}
	
	
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/product/o_update.do")
	public String update(Product bean, ProductExt ext, Long categoryId,Long promoteId,Long[] storeCategoryIds,
			String[] nature,Long[] picture,Integer stock[],Integer sales[],String[] color,Long[] character,
			String[] size,Long[] fashId,String[] colorImg,
			String fashionSwitchPic[],String fashionBigPic[],String fashionAmpPic[],
			Boolean[] isDefaults,Long[] colors,Long[] measures,Integer stockCounts[],Integer[] saleCounts,
			Double[] salePrices,Double[] marketPrices,Double[] costPrices,
			Long brandId, Long[] tagIds, String productKeywords, Long ctgId,String rightlist,String combinationrightlist, 
			@RequestParam(value = "file", required = false) MultipartFile file,Integer pageNo,
			HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateUpdate(bean.getId(), file, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		
		
		productKeywords = StringUtils.replace(productKeywords, MessageResolver
				.getMessage(request, "product.keywords.split"), LIST_SPLIT);
		String[] keywords = StringUtils.split(productKeywords, LIST_SPLIT);
		Map<String, String> exended = RequestUtils.getRequestMap(request, "exended_");
		Map<String, String> attr = RequestUtils.getRequestMap(request, "attr_");
		List li=new ArrayList(exended.keySet());
		String[] names = new String[li.size()];
		String[] values =  new String[li.size()];
		for(int i=0;i<li.size();i++){
		    names[i]=(String) li.get(i);
		    values[i]=exended.get(li.get(i));
		}
		 if(stockCounts!=null){
		    	bean.setStockCount(getstockCounts(stockCounts));
		    }
		bean = manager.update(bean, ext, categoryId, brandId, promoteId,storeCategoryIds,tagIds, keywords,names,values,attr,
				fashionSwitchPic,file);
		manager.updateCorrelation(bean,getProductIds(rightlist));
		manager.updateCombination(bean, getProductIds(combinationrightlist));
		List<ProductStandard> pcList=productStandardMng.findByProductId(bean.getId());
		for(int j=0;j<pcList.size();j++){
			productStandardMng.deleteById(pcList.get(j).getId());
		}
		if(picture!=null){
			for(int i =0;i<picture.length;i++){
				ProductStandard ps=new ProductStandard();
				ps.setImgPath(colorImg[i]);
				ps.setType(standardMng.findById(picture[i]).getType());
				ps.setProduct(bean);
				ps.setStandard(standardMng.findById(picture[i]));
				ps.setDataType(true);
				productStandardMng.save(ps);
			}
		}
	   if(character!=null){
		   for(int i =0;i<character.length;i++){
				ProductStandard ps=new ProductStandard();
				ps.setType(standardMng.findById(character[i]).getType());
				ps.setProduct(bean);
				ps.setStandard(standardMng.findById(character[i]));
				ps.setDataType(false);
				productStandardMng.save(ps);
			}
	   }
	   try{
		if(bean.getCategory().getColorsize()){
			java.util.Set<ProductFashion> pfList = bean.getFashions();
			if(fashId!=null){
				for(ProductFashion ps:pfList){
					if(!Arrays.asList(fashId).contains(ps.getId())){
						fashMng.deleteById(ps.getId());
					}
				}
			}else{
				for(ProductFashion ps:pfList){
						fashMng.deleteById(ps.getId());
				}
			}
			updateProductFash(bean,fashId,nature,isDefaults,stockCounts,salePrices,marketPrices,costPrices);
		}
	   }catch(ObjectNotFoundException e) {
		}catch(Exception e) {
			errors.addErrorString(manager.getTipFile("This.ChangeIsContainedInTheCaseOfTheDeletionOfTheGoods"));
			return errors.showErrorPage(model);	
		}
		log.info("update Product. id={}.", bean.getId());
		logMng.operating(request, "修改商品", "id="+bean.getId()+" ;name="+bean.getName());
		return list(ctgId,null,null,null,null,null,null,null,null,null,pageNo, request, model);
	}
	
	
	private void updateProductFash(Product bean,Long[] fashId,String[] nature,Boolean[] isDefaults,Integer[] stockCounts,
			Double[] salePrices,Double[] marketPrices,Double[] costPrices ){
		if(nature!=null){
			for(int i =0;i<nature.length;i++){
				String[] arr;
				ProductFashion pfash;
				if(fashId!=null&&i<fashId.length){
					pfash=productFashionMng.findById(fashId[i]);
					pfash.setCreateTime(new Date());
					pfash.setIsDefault(isDefaults[i]);
					pfash.setStockCount(stockCounts[i]);
					pfash.setMarketPrice(marketPrices[i]);
					pfash.setSalePrice(salePrices[i]);
					pfash.setCostPrice(costPrices[i]);
					pfash.setProductId(bean);
					pfash.setNature(nature[i]);
					arr=nature[i].split("_");
					productFashionMng.updateStandard(pfash, arr);
					if(isDefaults[i]){
						bean.setCostPrice(costPrices[i]);
						bean.setMarketPrice(marketPrices[i]);
						bean.setSalePrice(salePrices[i]);
						manager.update(bean);
					}
				}else{
					pfash = new ProductFashion();
					pfash.setCreateTime(new Date());
					pfash.setIsDefault(isDefaults[i]);
					pfash.setStockCount(stockCounts[i]);
					pfash.setMarketPrice(marketPrices[i]);
					pfash.setSalePrice(salePrices[i]);
					pfash.setCostPrice(costPrices[i]);
					pfash.setProductId(bean);
					pfash.setNature(nature[i]);
					arr=nature[i].split("_");
					ProductFashion fashion = productFashionMng.save(pfash,arr);
					productFashionMng.addStandard(fashion,arr);
					if(isDefaults[i]){
						bean.setCostPrice(costPrices[i]);
						bean.setMarketPrice(marketPrices[i]);
						bean.setSalePrice(salePrices[i]);
						manager.update(bean);
					}
				}
				
			}
		}
	}

	@RequestMapping("/product/o_delete.do")
	public String delete(Long[] ids, Long ctgId,Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Product[] beans;
		try {
			beans = manager.deleteByIds(ids);
			for (Product bean : beans) {
				log.info("delete Product. id={}", bean.getId());
			}
		} catch (Exception e) {
			return "redirect:v_error.do";
		}
		return list(ctgId,null,null,null,null,null,null,null,null,null,pageNo, request, model);
	}
	
	@RequestMapping(value = "/product/v_standardTypes_add.do")
	public String standardTypesAdd(Long categoryId,HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		   List<StandardType> standardTypeList = standardTypeMng.getList(categoryId);
		    model.addAttribute("standardTypeList", standardTypeList);
		    model.addAttribute("digit", standardTypeList.size());
		    response.setHeader("Cache-Control", "no-cache");
		    response.setContentType("text/json;charset=UTF-8");
		    return "product/standardTypes_add";
	}
	

	@RequestMapping("/product/o_create_index.do")
	public String createIndex(HttpServletRequest request,
			HttpServletResponse response, ModelMap model)
	        throws IOException, ParseException {
		Website web = SiteUtils.getWeb(request);
		String path = servletContext.getRealPath(Constants.LUCENE_JSPGOU);
		Directory dir = new SimpleFSDirectory(new File(path));
		boolean success = false;
		try {
			int count = luceneProductSvc.index(dir, web.getId(), null, null);
			model.addAttribute("count", count);
			success = true;
		} catch (CorruptIndexException e) {
			log.error("", e);
		} catch (LockObtainFailedException e) {
			log.error("", e);
		} catch (IOException e) {
			log.error("", e);
		}
		model.addAttribute("success", success);
		return "product/create_index_result";
	}
	
	@RequestMapping("/product/v_addFashion.do")
	public String addStyle(Long ctgId,Long productid, HttpServletRequest request, ModelMap model) {
		Product product = manager.findById(productid);
		model.addAttribute("pro", product);
		model.addAttribute("ctgId", ctgId);
		return "product/addFashion";
	}
	
	@RequestMapping("/product/o_saveFashion.do")
	public String saveFashion(Long ctgId,Long productid,String[] pro_name,String[] pro_value,ProductFashion fashion, 
			@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request,ModelMap model) {
		Website web=SiteUtils.getWeb(request);
		Product product = manager.findById(productid);
		StringBuffer propertys = new StringBuffer();
		if(pro_name!=null){
			for(int i = 0;i<pro_name.length;i++){
				propertys.append("@"+pro_name[i]+"??"+pro_value[i]);
			}
		}
		fashion.setFashionStyle(propertys.toString());
		fashion.setCreateTime(new Date());
		fashion.setProductId(product);
	//	productFashionMng.save(ctgId,fashion,file,web.getId());
		model.addAttribute("productid", productid);
		return "redirect:v_findFashion.do";
	}
	
	@RequestMapping("/product/v_findMySelfProperty.do")
	public String findMySelfProperty(Long productid,Long ctgId,Long typeid,HttpServletRequest request,ModelMap model){
		Website web = SiteUtils.getWeb(request);
		List<ProductTypeProperty> list = productTypePropertyMng.findListByTypeId(typeid);
		Product product = productMng.findById(productid);
		model.addAttribute("typeid", typeid);
		model.addAttribute("propertyList", list);
		model.addAttribute("ctgId", ctgId);
		model.addAttribute("uploadRoot", web.getUploadUrl());
		model.addAttribute("product", product);
		return "product/productPropertys";
	}
	
	@RequestMapping("/product/o_productExtUpdate.do")
	public String productExtUpdate(String[] picDescs,Long ctgId,Long productid,String[] pro_name,String[] pro_value,String[] picPaths,
			 HttpServletRequest request,ModelMap model){
		StringBuffer propertys = new StringBuffer();
		if(pro_name!=null){
			for(int i = 0;i<pro_name.length;i++){
				propertys.append("@"+pro_name[i]+"??"+pro_value[i]);
			}
		}
		StringBuffer imgs = new StringBuffer();
		if(picPaths!=null){
			for(int i = 0;i<picPaths.length;i++){
				imgs.append("@@"+picPaths[i]);
			}
		}
		StringBuffer imgdesc = new StringBuffer();
		if(picDescs!=null){
			for(int i = 0;i<picDescs.length;i++){
				if("".equals(picDescs[i])){
					picDescs[i]=" ";
				}
				imgdesc.append("@@"+picDescs[i]);
			}
		}
		Product product = productMng.findById(productid);
		ProductExt ext = product.getProductExt();
		ext.setProductProperty(propertys.toString());
		ext.setProductImgs(imgs.toString());
		ext.setProductImgDesc(imgdesc.toString());
		productExtMng.saveOrUpdate(ext, product);
		model.addAttribute("ctgId",ctgId);
		Website web = SiteUtils.getWeb(request);
		model.addAttribute("uploadRoot", web.getUploadUrl());
		return "redirect:v_list.do";
	}
	
	@RequestMapping("/product/o_delFashion.do")//异步删除商品款式(wangzewu)
	public String deleFashion(Long id,Long productId,HttpServletResponse response) throws JSONException{
		Boolean b=productFashionMng.getOneFash(productId);
		JSONObject j=new JSONObject();
		if(b!=null&&b){
			productFashionMng.deleteById(id);
			j.put("message", "删除成功！");
			j.put("boo", true);
				ResponseUtils.renderJson(response, j.toString());
				return null;
		}else{
			j.put("message", "必须留一款式！");
			j.put("boo", false);
			ResponseUtils.renderJson(response, j.toString());
			return null;
		}
	}
	
	@RequestMapping("/product/o_fashionUpdate.do")
	public String fashionUpdate(Long ctgId,String[] pro_name,String[] pro_value,ProductFashion fashion, 
			Long productid,Integer pageNo, HttpServletRequest request,
		ModelMap model) {
		
		StringBuffer propertys = new StringBuffer();
		if(pro_name!=null){
			for(int i = 0;i<pro_name.length;i++){
				propertys.append("@"+pro_name[i]+"??"+pro_value[i]);
			}
		}
		fashion.setProductId(productMng.findById(productid));
		fashion.setFashionStyle(propertys.toString());
		productFashionMng.update(fashion);
		model.addAttribute("pageNo", pageNo);
		model.addAttribute("productid", productid);
		model.addAttribute("ctgId", ctgId);
		return "redirect:v_findFashion.do";
	}

	@RequestMapping("/product/v_tuijian.do")
	public String tuijian(Long[] ids,Integer pageNo, HttpServletRequest request,
		ModelMap model) {
		List<ShopTuijian> list=shopTuijianMng.list();
		StringBuffer sb=new StringBuffer();
		for (int i = 0; i < ids.length; i++) {
			if (i!=ids.length-1) {
				sb=sb.append(ids[i].toString()).append(",");
			}else {
				sb=sb.append(ids[i].toString());
			}
		}
		model.addAttribute("list",list);
		model.addAttribute("pids", sb.toString());
		return "shopTuijian/tuijian";
	}
	
	
	
	

/**
 *  上架下架
 * @param id
 * @param pageNo
 * @param file
 * @param request
 * @param model
 * @return
 */
	@RequestMapping("/product/a_update.do")
	public String updateOnSale(Long id,Integer pageNo, @RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, ModelMap model) {
		Product bean=manager.findById(id);
		WebErrors errors = validateUpdate(bean.getId() ,file,request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
			
		if(bean.getOnSale()==false){
			bean.setOnSale(true);
		}else{
			bean.setOnSale(false);
		}
		bean = manager.update(bean);
		log.info("update Product. id={}.", bean.getId());
	    return	"redirect:v_list.do";
	}	
	//批量上架
	@RequestMapping("/product/v_shangjia.do")
	public String shangjia(Long[]ids,Integer pageNo, HttpServletRequest request,ModelMap model){
		for(Long id:ids){
			Product bean=manager.findById(id);
			bean.setOnSale(true);
			manager.update(bean);
		}
		return "redirect:v_list.do";
		
	}
	/**
	 * 批量下架
	 * @param ids
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/product/v_xiajia.do")
	public String xiajia(Long[]ids,Integer pageNo, HttpServletRequest request,ModelMap model){
		for(Long id:ids){
			Product bean=manager.findById(id);
				bean.setOnSale(false);
				manager.update(bean);	
		}
		return "redirect:v_list.do";
		
	}

	
	private WebErrors validateAdd(Long ctgId, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifNull(ctgId, "ctgId");
		if (errors.hasErrors()) {
			return errors;
		}
		Category ctg = categoryMng.findById(ctgId);
		errors.ifNotExist(ctg, Category.class, ctgId);
		return errors;
	}

	private WebErrors validateSave(Product bean, MultipartFile file,
			HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (file != null && !file.isEmpty()) {
			String name = file.getOriginalFilename();
			vldImage(name, errors);
		}
		bean.setWebsite(SiteUtils.getWeb(request));
		return errors;
	}

	private WebErrors validateEdit(Long id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifNull(id, "id");
		vldExist(id, errors);
		return errors;
	}

	private WebErrors validateUpdate(Long id, MultipartFile file,
			HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifNull(id, "id");
		if (file != null && !file.isEmpty()) {
			String name = file.getOriginalFilename();
			vldImage(name, errors);
			if (errors.hasErrors()) {
				return errors;
			}
		}
		vldExist(id, errors);
		return errors;
	}

	private WebErrors validateDelete(Long[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Long id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private void vldExist(Long id, WebErrors errors) {
		if (errors.hasErrors()) {
			return;
		}
		Product entity = manager.findById(id);
		errors.ifNotExist(entity, Product.class, id);
	}

	private void vldImage(String filename, WebErrors errors) {
		if (errors.hasErrors()) {
			return;
		}
		String ext = FilenameUtils.getExtension(filename);
		if (!ImageUtils.isImage(ext)) {
			errors.addErrorString("not support image extension:" + filename);
		}
	}
	
	public Long[] getProductIds(String rightlist){
		String[] arr;
		arr = rightlist.split(",");
		Long productIds[]  = new Long[arr.length] ; 
		for(int i=0,j=arr.length;i<j;i++){
			if(!arr[i].equals("")){
				productIds[i] = Long.parseLong(arr[i]);
			}
		}
		return productIds;
	}
	
	@Autowired
	private StandardMng standardMng;
	@Autowired
	private StandardTypeMng standardTypeMng;
	@Autowired
	private ProductFashionMng fashMng;
	@Autowired
	private LuceneProductSvc luceneProductSvc;
	@Autowired
	private ProductTagMng productTagMng;
	@Autowired
	private CategoryMng categoryMng;
	@Autowired
	private ProductMng manager;
	@Autowired
	private ProductTypePropertyMng productTypePropertyMng;
	@Autowired
	private ProductExtMng productExtMng; 
	@Autowired
	private ProductMng productMng;
	@Autowired
	private ProductFashionMng productFashionMng;
	@Autowired
	private ProductTypeMng productTypeMng;
	@Autowired
	private ExendedMng exendedMng;
	@Autowired
	private ProductStandardMng productStandardMng;
	@Autowired
	private ShopTuijianMng shopTuijianMng;
	@Autowired
	private BrandMng brandMng;
	@Autowired
	private LogMng logMng;
	
	private ServletContext servletContext;
	
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
}